package presentation;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import db.DbUtils;
import db.Picture;

public class DeletePictureServlet extends javax.servlet.http.HttpServlet
		implements javax.servlet.Servlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		Session hbSession = DbUtils.startSession();
		Long imageId = Long.parseLong(request.getParameter("image"));
		Picture pic=DbUtils.getPicturebyId(hbSession, imageId);
		try {
			String format = DbUtils.getPicturebyId(hbSession, imageId).getPictureFormat();
			DbUtils.deletePicture(hbSession, imageId);
			hbSession.getTransaction().commit();
			String path = this.getServletContext().getInitParameter("IMAGES_DIRECTORY");
			path = this.getServletContext().getRealPath(path);
    		File pictureFile = new File(path + File.separatorChar + imageId + "." + format);
    		File deletedDir = new File(path + File.separatorChar + "deleted");
    		deletedDir.mkdir();
    		pictureFile.renameTo(new File(deletedDir.getAbsolutePath() + File.separatorChar + imageId + "." + format));
    		pictureFile = new File(path + File.separatorChar + "m_" +  imageId + "." + format);
    		pictureFile.delete();
    		pictureFile = new File(path + File.separatorChar + "s_" +  imageId + "." + format);
    		pictureFile.delete();
			response.sendRedirect("Home.jsp?album_id="+pic.getAlbum().getAlbumId());
		} catch (Exception e) {
			if (hbSession != null) {
				hbSession.getTransaction().rollback();
				hbSession.close();
			}
			response.sendRedirect("Error.jsp?msg=image");
			e.printStackTrace();
		}
	}
}